package com.miyake.loveviewweb.shared.model;

import java.io.Serializable;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.Key;

import org.slim3.datastore.Attribute;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.Model;
import org.slim3.util.BeanUtil;
import org.slim3.util.CopyOptions;

@Model(schemaVersion = 1)
public class UploadedFile implements Serializable {

    public String getBlobKey() {
        return blobKey;
    }

    public void setBlobKey(String blobKey) {
        this.blobKey = blobKey;
    }

    private static final long serialVersionUID = 1L;

    @Attribute(primaryKey = true)
    private Key key;

    @Attribute(version = true)
    private Long version;

    private String blobKey;

    /**
     * Returns the key.
     *
     * @return the key
     */
    public Key getKey() {
        return key;
    }

    /**
     * Sets the key.
     *
     * @param key
     *            the key
     */
    public void setKey(Key key) {
        this.key = key;
    }

    /**
     * Returns the version.
     *
     * @return the version
     */
    public Long getVersion() {
        return version;
    }

    /**
     * Sets the version.
     *
     * @param version
     *            the version
     */
    public void setVersion(Long version) {
        this.version = version;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((key == null) ? 0 : key.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        UploadedFile other = (UploadedFile) obj;
        if (key == null) {
            if (other.key != null) {
                return false;
            }
        } else if (!key.equals(other.key)) {
            return false;
        }
        return true;
    }
    
    public String getServeURL() {
        return String.format("/blobstore/serve?blobKey=%s", blobKey);
    }

    public static Key createKey(BlobKey blobKey) {
        return Datastore.createKey(UploadedFile.class, blobKey.getKeyString());
    }

    public static UploadedFile getInstance(BlobKey blobKey) {
        BlobInfoFactory factory = new BlobInfoFactory();

        UploadedFile model = new UploadedFile();
        model.setBlobKey(blobKey.getKeyString());
        BlobInfo blobInfo = factory.loadBlobInfo(blobKey);
        BeanUtil.copy(blobInfo, model, new CopyOptions().exclude("blobKey"));
        return model;
    }

}
